package com.google.code.netbuilder.dal.providers.jpa;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.google.code.netbuilder.dal.entities.Cable;
import com.google.code.netbuilder.dal.providers.ICableProvider;

/**
 * Class is JPA implementation of DAO for Cable Entity
 * Uses EntityManager from PersistenceContext
 * @author Sergey Kozlov
 * 
 *
 */
@Stateless
public class CableProviderJPA implements ICableProvider, Serializable{

	private static final long serialVersionUID = 8678205432644305216L;
	
	@PersistenceContext(unitName = "NetBuilder")
    EntityManager em;

	@Override
	public void save(Cable entity) throws RuntimeException {
		em.persist(entity);
	}

	@Override
	public void update(Cable entity) throws RuntimeException {
		em.merge(entity);		
	}

	@Override
	public void delete(Cable entity) throws RuntimeException {
		em.remove(entity);
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cable> findAll() throws RuntimeException {
		Query q = em.createQuery("select c from Cable c");		
		return (List<Cable>)q.getResultList();
	}

	@Override
	public Cable findByID(Integer id) throws RuntimeException {
		Query q = em.createQuery("select c from Cable c where c.id = :id").setParameter("id", id);		
		return (Cable)q.getSingleResult();
	}
}
